package com.stoney.http;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created by Stony on 2015/12/12.
 */
public class NetworkDispatcher extends Thread{
    private boolean quit = false;

    private final BlockingQueue<Request> mQueue;
    /** The network interface for processing requests. */
    private final BasicNetwork mNetwork;
    private final ResponseDelivery mDelivery;

    public NetworkDispatcher(PriorityBlockingQueue<Request> networkQueue, BasicNetwork network, ResponseDelivery delivery) {
        mQueue = networkQueue;
        mNetwork = network;
        mDelivery = delivery;
    }

    @Override
    public void run() {
        //setPriority(MIN_PRIORITY);
        Request request;
        while (true) {
            try {
                // Take a request from the queue.
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (quit) {
                    return;
                }
                continue;
            }
            try{
                request.addMarker("network-queue-take");

                // If the request was cancelled already, do not perform the
                // network request.
                if (request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                    continue;
                }

                NetworkResponse networkResponse = mNetwork.performRequest(request);

                // Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");

                // Post the response back.
                request.markDelivered();
                mDelivery.postResponse(request, response);
            }catch (Exception e){
                mDelivery.postError(request, new RequestFailureError(e));
            }
        }
    }

    public void quit() {
        this.quit = true;
        interrupt();
    }

}
